package org.ifilm.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.ifilm.model.Message;
import org.ifilm.model.MessageSubject;
import org.ifilm.model.User;
import org.ifilm.service.MessageService;
import org.ifilm.service.UserService;
import org.ifilm.util.GeneralConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * @author Mustafa Genç
 *
 */
@Controller
@RequestMapping("/message/**")
public class MessageController {
	@Autowired
	private MessageService messageService;
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value = "/createMessage", method = {RequestMethod.POST, RequestMethod.GET})
	public ResponseEntity<Map<String, Object>> createProject(@RequestParam Long receiverId, @RequestParam(value = "message") String messageText, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> responseBody = new HashMap<String, Object>();
		
		//sender
		User loggedUser = getLoggedUser(request);
		
		if (loggedUser != null) {
			User receiver = userService.getUserById(receiverId);
			
			if (receiver != null) {
				String messageSubjectId = request.getParameter("messageSubjectId");
				
				MessageSubject messageSubject = null;
				
				if (StringUtils.isNotBlank(messageSubjectId)) {
					try {
						messageSubject = messageService.getMessageSubject(Long.parseLong(messageSubjectId));
					} catch (NumberFormatException e) {
						return null;
					}
				} else {
					messageSubject = new MessageSubject();
					messageSubject.setSubject(request.getParameter("subject"));
					messageSubject.setSender(loggedUser);
					messageSubject.setReceiver(receiver);
					messageSubject.setCreationTime(new Date());
					
					messageSubject = messageService.createMessageSubject(messageSubject);
				}
				
				messageSubject.setHasUnread(true);
				messageSubject.setUpdateTime(new Date());
				messageSubject.setLastSenderId(loggedUser.getId());
				messageSubject.setLastReceiverId(receiver.getId());
				
				Message message = new Message();
				message.setSenderId(loggedUser.getId());
				message.setReceiverId(receiver.getId());
				message.setMessage(messageText);
				
				message.setStatus(0);
				message.setCreationTime(new Date());
				
				message = messageService.createMessage(message);
				
				if (message != null) {
					messageService.updateMessages(messageSubject, message);
					responseBody.put("status", "success");
				}
			}
		}
		
		return new ResponseEntity<Map<String, Object>>(responseBody, HttpStatus.OK);
	}
	
	@RequestMapping(value = "/getMessageSubject", method = {RequestMethod.POST, RequestMethod.GET})
	public ResponseEntity<Map<String, Object>> createProject(@RequestParam Long messageSubjectId, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> responseBody = new HashMap<String, Object>();
		
		MessageSubject messageSubject = messageService.getMessageSubject(messageSubjectId);
		responseBody.put("subject", messageSubject);
		
		if (getLoggedUser(request).getId() == messageSubject.getLastReceiverId()) {
			messageService.setRead(messageSubject);
		}
		
		return new ResponseEntity<Map<String, Object>>(responseBody, HttpStatus.OK);
	}
	
	@RequestMapping(value = "/getMessages", method = {RequestMethod.POST, RequestMethod.GET})
	public ModelAndView getMessages(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView result = new ModelAndView("/messages.jsp");
		
		//sender
		User loggedUser = getLoggedUser(request);
		
		if (loggedUser != null) {
			List<MessageSubject> messageSubjects = messageService.getMessageSubjects(loggedUser.getId());
			
			result.addObject("messageSubjects", messageSubjects);
		}
		
		return result;
	}
	
	@RequestMapping(value = "/getUnreadMessageCount", method = {RequestMethod.POST, RequestMethod.GET})
	public ResponseEntity<Map<String, Object>> createProject(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> responseBody = new HashMap<String, Object>();
		
		User loggedUser = getLoggedUser(request);
		
		if (loggedUser != null) {
			List<MessageSubject> messageSubjects = messageService.getUnreadMessages(loggedUser.getId());
			
			responseBody.put("count", messageSubjects.size());
		}
		
		return new ResponseEntity<Map<String, Object>>(responseBody, HttpStatus.OK);
	}
	
	private User getLoggedUser(HttpServletRequest request) {
		HttpSession session = request.getSession();
		
		return (User) session.getAttribute(GeneralConstants.user);
	}
}